package org.example;

public class Test1 {
    //leetcode 最后一个单词的长度 https://leetcode.cn/problems/length-of-last-word/description/?envType=study-plan-v2&envId=top-interview-150
    /**
     * 直接使用内置方法
     * @param s
     * @return
     */
    public int lengthOfLastWord(String s) {
        s = s.trim();
        return s.length()-s.lastIndexOf(' ')-1;
    }

    /**
     * 正向遍历
     * @param s
     * @return
     */
    public int lengthOfLastWord1(String s) {
        int len = 0, index = 0;
        while (index < s.length()) {
            if (s.charAt(index) == ' ') {
                while (index < s.length() && s.charAt(index) == ' ') {
                    index++;
                }
                len = s.length() == index ? len : 0;
            }else {
                index++;
                len++;
            }
        }
        return len;
    }

    /**
     * 直接方向便利找到最后一个单词的最后一个字母
     * @param s
     * @return
     */
    public int lengthOfLastWord2(String s) {
        int len = s.length();
        int index = len-1, ret = 0;
        while (index >= 0 && s.charAt(index) == ' ') index--;
        while (index >= 0 && s.charAt(index) != ' ') {
            index--;
            ret++;
        }
        return ret;
    }

    public static void main(String[] args) {
        Test1 test1 = new Test1();
        System.out.println(test1.lengthOfLastWord("hello world"));
        System.out.println(666);
    }
}
